/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */
package cn.hermit.util;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * File utility 
 * 
 * @author Jack Gao (Chinese name : GAO JIANGUO, Email : linux.gjg@gmail.com)
 * @date 24 Jul, 2014
 */
public class FileUtils {

	/**
	 * Get files through directory URL recursively
	 * 
	 * @param url
	 * 		File URL
	 * @param recursive
	 * 		If true, will get files recursively
	 * @param includingDir
	 * 		If true, will get sub directories
	 * @return
	 * 		FileUtils under directory with URL
	 */
	public static List<File> getFiles(URL url, boolean recursive,
			boolean includingDir) {
		if (url == null || !"file".equals(url.getProtocol()))
			return Collections.emptyList();
		if (recursive) {
			return getFiles(new File(url.getFile()), includingDir);
		} else {
			File dir = new File(url.getFile());
			if (dir.exists()) {
				if (dir.isDirectory()) {
					return Arrays.asList(dir.listFiles());
				} else {
					return Arrays.asList(dir);
				}
			} else {
				return Collections.emptyList();
			}
		}
	}

	/**
	 * Get files under directory
	 * @param dir
	 * 		The directory
	 * @param includingDir
	 * 		If true, will get sub directories
	 * @return
	 * 		FileUtils under directory
	 */
	public static List<File> getFiles(File dir, boolean includingDir) {
		if (dir == null || !dir.exists()) {
			return Collections.emptyList();
		}
		if (dir.isDirectory()) {
			List<File> files = new ArrayList<File>();
			getFiles(dir, files, includingDir);
			return files;
		} else {
			return Arrays.asList(dir);
		}
	}

	/*
	 * Get files recursively
	 * 
	 * @param dir
	 * @param files
	 */
	private static void getFiles(File dir, List<File> files,
			boolean includingDir) {
		if (dir == null || !dir.exists() || !dir.isDirectory()) {
			return;
		}
		for (File f : dir.listFiles()) {
			if (f.isDirectory()) {
				if (includingDir) {
					files.add(f);
				}
				getFiles(f, files, includingDir);
			} else {
				files.add(f);
			}
		}
	}
	
}